package com.mybatisplus.controller;

import com.mybatisplus.entity.BaseResultBean;
import com.mybatisplus.entity.Student;
import com.mybatisplus.service.StudentService;
import com.mybatisplus.vo.DataVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Create By GuoZhengRong
 * File was Created on {YEAR} {DATE} {TIME}
 * Create By IntelliJ IDEA
 **/
@RequestMapping("/studentData")
@RestController
public class StudentDataController {
    @Autowired
    private StudentService studentService;

    //    1.查询全部数据
    @RequestMapping("/studentlist")
    public DataVO<List> list(HttpServletRequest request/*, HttpServletResponse response*/) {
        DataVO<List> dataVO = new DataVO<>();
        String page = request.getParameter("page");
        String limit = request.getParameter("limit");
        try {
            dataVO = studentService.findData(Integer.valueOf(page), Integer.valueOf(limit));
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return dataVO;
    }

    @PostMapping("/import")
    public BaseResultBean importFromExcel(@RequestBody Student student) {
        synchronized (this) {
            BaseResultBean baseResultBean = new BaseResultBean();
            String studentName = studentService.selectNameByStuid(student.getStuid());
            try {
                if (student.getName().equals(studentName)) {
                    //如果学生存在，将更新其分数并返回信息到浏览器
                    System.out.println(studentName);
                    baseResultBean.setStatus(false);
                    baseResultBean.setMessage("已更新分数");
                    studentService.updateScoreByStuid(student.getScore(), student.getStuid());
                } else {
                    //学生不存在，添加学生到数据库并返回信息到浏览器
                    System.out.println(studentName);
                    studentService.insertToTable(student);
                    baseResultBean.setMessage("导入成功");
                    baseResultBean.setStatus(true);
                }
            } catch (Exception e) {
                baseResultBean.setMessage("导入失败");
                baseResultBean.setStatus(false);
            }
            return baseResultBean;
        }
    }

    //    2.数据可视化的数据传输
    @GetMapping("/studentdata")
    public List<Student> selectScore() {
        return studentService.SelectScore();
    }
}
